package com.gua.user.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.gua.user.mapper.ManagementMenuMapper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gua.user.entity.Role;
import com.gua.user.entity.User;
import com.gua.user.mapper.MenuMapper;
import com.gua.user.mapper.RoleMapper;
import com.gua.user.mapper.UserMapper;
import com.gua.user.response.LoginUser;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    
	@Autowired
    private UserMapper userMapper;
    
//	@Autowired
//    private MenuMapper menuMapper;

    @Autowired
    private ManagementMenuMapper managementMenuMapper;
	
	@Autowired
	private RoleMapper roleMapper;
    
	@Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, username);
        User user = userMapper.selectOne(queryWrapper);
        //如果查询不到数据就通过抛出异常来给出提示
        if(Objects.isNull(user)){
            throw new RuntimeException("用户名或密码错误");
        }
        //根据用户查询权限信息 添加到LoginUser中
        List<String> permissions = managementMenuMapper.selectPermsByUserId(user.getId());
        if(CollectionUtils.isEmpty(permissions)) {
        	permissions = new ArrayList<>();
        }
        permissions = permissions.stream()
        		.filter(StringUtils::isNotEmpty)
        		.collect(Collectors.toList());
        //获取用户的角色
        List<Role> roles = roleMapper.getRoleByUserId(user.getId());
        if(CollectionUtils.isEmpty(roles)) {
        	roles = new ArrayList<>();
        }
        //封装成UserDetails对象返回
        return new LoginUser(user, permissions, roles);
    }
}
